package cn.cvs.serevlet;

import cn.cvs.dao.MovieMapper;
import cn.cvs.pojo.Movie;
import cn.cvs.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet (urlPatterns = "/MovieAddServlet")
public class MovieAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        SqlSession sqlSession = MyBatisUtil.createSqlSession();
        MovieMapper movieMapper = sqlSession.getMapper(MovieMapper.class);
        PrintWriter out = resp.getWriter();
        Movie movie = new Movie();
        movie.setMovieName(req.getParameter("movieName"));
        movie.setMovieType(req.getParameter("movieType"));
        movie.setPrice(Double.parseDouble(req.getParameter("price")));
        movie.setRecommend(Integer.parseInt(req.getParameter("recommend")));
        movie.setStartTime(req.getParameter("startTime"));
        movie.setEndTime(req.getParameter("endTime"));
        try {
            int num =movieMapper.addMovie(movie);
            if (num>0){
                out.print("<script>\n" +
                        "    location.href='MovieLimitServlet';\n" +
                        "    alert(\"添加成功!\")\n" +
                        "  </script>");
            }else {
                out.print("<script>\n" +
                        "    location.href='MovieLimitServlet';\n" +
                        "    alert(\"添加失败!\")\n" +
                        "  </script>");
            }
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally {
            out.flush();
            out.close();
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
